//
//  LoginViewController.m
//  SuningBeaulty
//
//  Created by HappyMilk 02 on 2017/4/13.
//  Copyright © 2017年 HappyMilk 02. All rights reserved.
//

#import "LoginViewController.h"
#import "PublicTool.h"
#import "WeChatQQStaticLibHeader.h"
#import "UIViewController+XLBubbleTransition.h"

@interface LoginViewController ()<UIScrollViewDelegate>{
    UIColor * m_mainColor;
    BOOL m_isOpenRegister;
}

@property (weak, nonatomic) IBOutlet UIScrollView *scrollview;
@property (weak, nonatomic) IBOutlet UIView *view_scroll;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *view_scroll_height;

//登陆
@property (weak, nonatomic) IBOutlet UITextField *login_user_tf;
@property (weak, nonatomic) IBOutlet UITextField *login_psd_tf;
@property (weak, nonatomic) IBOutlet UIButton *login_btn;

//
@property (weak, nonatomic) IBOutlet UIImageView *img_xia;
@property (weak, nonatomic) IBOutlet UIButton *btn_xia;

//注册
@property (nonatomic ,strong) UITextField *register_user_tf;
@property (nonatomic ,strong) UITextField *register_psd_tf;
@property (nonatomic ,strong) UIButton *register_btn;

//跳过按钮
@property (nonatomic ,strong) UIButton *skilp;

@end

@implementation LoginViewController
- (IBAction)popvc:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];m_isOpenRegister = YES;
    ADD_OBSERVER(self, @selector(onAppInfoLoadedCB:), NOTIFICATION_APP_INFO_LOADED, nil);
    ADD_OBSERVER(self, @selector(onUserLoginSuccessCB:), NOTIFICATION_USER_LOGIN_SUCCESS, nil);
    
    //创建注册视图
    [self createRegisterView];
    
    //修改视图
    [self ModifyView];
    
    
}
#pragma mark 用户登录成功回调，在这里可以获取用户的唯一ID
-(void)onUserLoginSuccessCB:(id)sender{

}
#pragma mark 初始化成功回调打开登陆
- (void)onAppInfoLoadedCB:(id)sender{
    if([WeChatQQApi stander].m_loginType != LT_NONE){
        m_isOpenRegister = NO;
        self.scrollview.scrollEnabled = NO;
    }
    if([WeChatQQApi stander].m_isLogin == NO){
        
        if([WeChatQQApi stander].m_loginType == LT_QQ){
            [self createThirdLoginBtn:YES];
        }
        else if([WeChatQQApi stander].m_loginType == LT_WECHAT || [WeChatQQApi stander].m_loginType == LT_MP || [WeChatQQApi stander].m_loginType == LT_WECHAT_SCAN){
            [self createThirdLoginBtn:NO];
            
        }
    }
}
- (void)createThirdLoginBtn:(BOOL )isQQ{
    
    UIButton *btn = [[UIButton alloc] initWithFrame:(CGRect){__kwidth/2-40,self.login_btn.frame.origin.y+120,80,80}];
    if (isQQ) {
        [btn setImage:[UIImage imageNamed:@"qQlogo.png"] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(qqLoginAction) forControlEvents:UIControlEventTouchUpInside];
        [self.view_scroll addSubview:btn];
    }else{
        [btn setImage:[UIImage imageNamed:@"logo.png"] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(wechatAction) forControlEvents:UIControlEventTouchUpInside];
        [self.view_scroll addSubview:btn];
    }
}
- (void)wechatAction{
    if([WeChatQQApi stander].m_isLogin == NO){
        if([WeChatQQApi stander].m_loginType == LT_WECHAT){
            if (isPad) {
                QRCodeLoginIPadViewController * qrCodeLoginViewController = [[QRCodeLoginIPadViewController alloc]initWithNibName:@"QRCodeLoginIPadViewController" bundle:nil];
                qrCodeLoginViewController.m_color = m_mainColor;
                UINavigationController * qrCodeNavigationController = [[UINavigationController alloc]initWithRootViewController:qrCodeLoginViewController];
                [self presentViewController:qrCodeNavigationController animated:YES completion:nil];
            }
            else{
                QRCodeLoginViewController * qrCodeLoginViewController = [[QRCodeLoginViewController alloc]initWithNibName:@"QRCodeLoginViewController" bundle:nil];
                [qrCodeLoginViewController updateSaveBtnColor:m_mainColor];
                UINavigationController * qrCodeNavigationController = [[UINavigationController alloc]initWithRootViewController:qrCodeLoginViewController];
                [self presentViewController:qrCodeNavigationController animated:YES completion:nil];
            }
        }
        else if([WeChatQQApi stander].m_loginType == LT_MP){
            if (isPad) {
                QRCodeLoginIPadViewController * qrCodeLoginViewController = [[QRCodeLoginIPadViewController alloc]initWithNibName:@"QRCodeLoginIPadViewController" bundle:nil];
                qrCodeLoginViewController.m_color = m_mainColor;
                UINavigationController * qrCodeNavigationController = [[UINavigationController alloc]initWithRootViewController:qrCodeLoginViewController];
                [self presentViewController:qrCodeNavigationController animated:YES completion:nil];
            }
            else{
                MPLoginViewController * qrCodeLoginViewController = [[MPLoginViewController alloc]initWithNibName:@"MPLoginViewController" bundle:nil];
                [qrCodeLoginViewController updateSaveBtnColor:m_mainColor];
                UINavigationController * qrCodeNavigationController = [[UINavigationController alloc]initWithRootViewController:qrCodeLoginViewController];
                [self presentViewController:qrCodeNavigationController animated:YES completion:nil];
            }
        }
        else if([WeChatQQApi stander].m_loginType == LT_WECHAT_SCAN){
            QRCodeLoginIPadViewController * qrCodeLoginViewController = [[QRCodeLoginIPadViewController alloc]initWithNibName:@"QRCodeLoginIPadViewController" bundle:nil];
            qrCodeLoginViewController.m_color = m_mainColor;
            UINavigationController * qrCodeNavigationController = [[UINavigationController alloc]initWithRootViewController:qrCodeLoginViewController];
            [self presentViewController:qrCodeNavigationController animated:YES completion:nil];
        }
    }
}
- (void)qqLoginAction{
    QQLoginViewController * qqLoginViewController = [[QQLoginViewController alloc]initWithNibName:@"QQLoginViewController" bundle:nil];
    [qqLoginViewController updateMainColor:m_mainColor];
    UINavigationController * qqNavigationController = [[UINavigationController alloc]initWithRootViewController:qqLoginViewController];
    [self presentViewController:qqNavigationController animated:YES completion:nil];
}
- (void)createRegisterView{
    
    self.register_user_tf = [[UITextField alloc] initWithFrame:(CGRect){__kwidth/2-130,__kheight+184,260,30}];
    self.register_user_tf.placeholder = @"Enter Username";
    [self.register_user_tf setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
    [self.view_scroll addSubview:self.register_user_tf];
    
    UIView *view = [[UIView alloc] initWithFrame:(CGRect){__kwidth/2-130,__kheight+218,260,1}];
    view.backgroundColor = [UIColor whiteColor];
    [self.view_scroll addSubview:view];
    
    self.register_psd_tf = [[UITextField alloc] initWithFrame:(CGRect){__kwidth/2-130,__kheight+218+36,260,30}];
    self.register_psd_tf.placeholder = @"Enter Password";
    [self.register_psd_tf setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
    [self.view_scroll addSubview:self.register_psd_tf];
    
    UIView *view1 = [[UIView alloc] initWithFrame:(CGRect){__kwidth/2-130,__kheight+218+36+34,260,1}];
    view1.backgroundColor = [UIColor whiteColor];
    [self.view_scroll addSubview:view1];
    
    self.register_btn = [[UIButton alloc] initWithFrame:(CGRect){__kwidth/2-130,__kheight+218+36+34+46,260,40}];
    [self.register_btn setTitle:@"Register" forState:UIControlStateNormal];
    self.register_btn.layer.masksToBounds = YES;
    self.register_btn.layer.cornerRadius = 8;
    self.register_btn.layer.borderColor = [UIColor whiteColor].CGColor;
    self.register_btn.layer.borderWidth = 1;
    [self.register_btn addTarget:self action:@selector(registerAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view_scroll addSubview:self.register_btn];
    
//    self.skilp = [[UIButton alloc] initWithFrame:(CGRect){__kwidth-80,400,60,60}];
//    self.skilp.layer.masksToBounds = YES;
//    self.skilp.layer.cornerRadius = 30;
//    self.skilp.layer.borderWidth = 1;
//    self.skilp.layer.borderColor = [UIColor whiteColor].CGColor;
//    [self.skilp setTitle:@"Skip" forState:UIControlStateNormal];
//    [self.skilp addTarget:self action:@selector(skilpAction) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:self.skilp];
//    
//    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(moveSkilpBtn:)];
//    [self.skilp addGestureRecognizer:pan];
    
}
- (void)moveSkilpBtn:(UIGestureRecognizer *)swipe{
    CGPoint point = [swipe locationInView:self.view];
    self.skilp.center = point;
}
//跳过
- (void)skilpAction{
    
    self.xl_pushTranstion = [XLBubbleTransition transitionWithAnchorRect:self.skilp.frame];
    self.xl_popTranstion = [XLBubbleTransition transitionWithAnchorRect:self.skilp.frame];
    
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    UIViewController *vc = [sb instantiateViewControllerWithIdentifier:@"HomeViewController"];
    [self.navigationController pushViewController:vc animated:YES];
}

//注册
- (void)registerAction{
    if (self.register_user_tf.text.length >= 6 && self.register_psd_tf.text.length >= 6) {
        
        NSString * username = self.register_user_tf.text;
        NSString * password = self.register_psd_tf.text;
        
        if (username && password) {
            SHOW_HUD(@"Is registering...");
            
            [[AsyncLeanCloudSimulationService stander]asyncRegisterLeanCloud:username password:password respBlock:^(LEANCLOUD_REGISTER_RESULT result) {
                HIDE_HUD;
                if (result == LRR_NOT_INIT) {
                    NSString *msg = @"The network does not seem to work. Please try again later";
                    NSString *hint = @"Hint";
                    UIAlertView *alertview = [[UIAlertView alloc] initWithTitle:hint message:msg delegate:nil cancelButtonTitle:@"Confirm" otherButtonTitles:nil, nil];
                    [alertview show];
                }
                else if (result == LRR_SUCCESS) {
                    UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:@"Hint" message:@"registration success! please sign in！" delegate:nil cancelButtonTitle:@"Confirm" otherButtonTitles:nil];
                    [alertView show];
                    
                    [self dismissViewControllerAnimated:YES completion:nil];
                }
                else{
                    UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:@"Hint" message:@"failure! Username already exists! Please try again!" delegate:nil cancelButtonTitle:@"Confirm" otherButtonTitles:nil];
                    [alertView show];
                }
            }];
        }
    } else {
        SHOW_HUD_MESSAGE(@"Please fill in the correct account or password! Account password must be less than 6!");
    }
}
//登陆
- (IBAction)loginAction:(id)sender {
    if (self.login_user_tf.text.length >= 6 && self.login_psd_tf.text.length >= 6) {
        
        NSString *username = self.login_user_tf.text;
        NSString *password = self.login_psd_tf.text;
        
        if (username && password) {
            
            SHOW_HUD(NSLocalizedStringFromTable(@"logging in...", @"HHLeanCloud", nil));
            
            
            [[AsyncLeanCloudSimulationService stander]asyncLoginLeanCloud:username password:password respBlock:^(LEANCLOUD_LOGIN_RESULT result) {
                HIDE_HUD;
                
                NSString *hint = NSLocalizedStringFromTable(@"Hint", @"HHLeanCloud", nil);
                NSString *msg = NSLocalizedStringFromTable(@"login successful", @"HHLeanCloud", nil);
                NSString *confirm = NSLocalizedStringFromTable(@"Confirm", @"HHLeanCloud", nil);
                
                if(result == LLR_NOT_INIT){
                    NSString *msg = NSLocalizedStringFromTable(@"The network does not seem to work. Please try again later", @"HHLeanCloud", nil);
                    
                    UIAlertView *alertview = [[UIAlertView alloc] initWithTitle:hint message:msg delegate:nil cancelButtonTitle:confirm otherButtonTitles:nil, nil];
                    [alertview show];
                }
                else if (result == LLR_SUCCESS) {
                    
                    UIAlertView *alertview = [[UIAlertView alloc] initWithTitle:hint message:msg delegate:nil cancelButtonTitle:confirm otherButtonTitles:nil, nil];
                    [alertview show];
                    //普通登陆成功
                    
                    
                    
                    
                }else{
                    
                    NSString *msg = NSLocalizedStringFromTable(@"Username or password is wrong!", @"HHLeanCloud", nil);
                    
                    UIAlertView *alertview = [[UIAlertView alloc] initWithTitle:hint message:msg delegate:nil cancelButtonTitle:confirm otherButtonTitles:nil, nil];
                    [alertview show];
                }
            }];
        }
    }
    else
    {
        NSString *msg = NSLocalizedStringFromTable(@"Please fill in the correct account or password! Account password must be less than 6!", @"HHLeanCloud", nil);
        SHOW_HUD_MESSAGE(msg);
    }
}

- (void)ModifyView{
    
    self.view_scroll_height.constant = __kheight*2;
    self.login_btn.layer.masksToBounds = YES;
    self.login_btn.layer.cornerRadius = 8;
    self.login_btn.layer.borderColor = [UIColor whiteColor].CGColor;
    self.login_btn.layer.borderWidth = 1;
    [self.login_user_tf setValue:[UIColor whiteColor]forKeyPath:@"_placeholderLabel.textColor"];
    [self.login_psd_tf setValue:[UIColor whiteColor]forKeyPath:@"_placeholderLabel.textColor"];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(resignFirstTF)];
    [self.view_scroll addGestureRecognizer:tap];
}

//滑动到注册页面按钮
- (IBAction)scrollRegister:(id)sender {
    if (m_isOpenRegister == NO) {
        UIAlertView *alertview = [[UIAlertView alloc] initWithTitle:@"提示" message:@"服务器维护暂时停用注册功能！老用户可正常登录！新用户请使用第三方登录！" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertview show];
    }
    else{
        [self.scrollview setContentOffset:(CGPoint){0,__kheight} animated:YES];
        self.img_xia.hidden = YES;
        self.btn_xia.hidden = YES;
    }
    
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    CGFloat point_y = scrollView.contentOffset.y;
    NSInteger index = point_y/__kheight;
    NSLog(@"--- %ld",(long)index);
    if (index == 1){
        self.img_xia.hidden = YES;
        self.btn_xia.hidden = YES;
    }else{
        self.img_xia.hidden = NO;
        self.btn_xia.hidden = NO;
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)resignFirstTF{
    [self.login_user_tf resignFirstResponder];
    [self.login_psd_tf resignFirstResponder];
    [self.register_user_tf resignFirstResponder];
    [self.register_psd_tf resignFirstResponder];
}

- (IBAction)userAgreement:(id)sender {
    
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    UIViewController *vc = [sb instantiateViewControllerWithIdentifier:@"PrivacyViewController"];
    vc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentViewController:vc animated:YES completion:nil];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/


@end
